package top.lishuoboy.knife4j.swagger3_0_0.advice;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import top.lishuoboy.knife4j.swagger3_0_0.annotation.NotResponseBodyAdvice;
import top.lishuoboy.knife4j.swagger3_0_0.controller.MyUserController;
import top.lishuoboy.knife4j.swagger3_0_0.enums.Code;
import top.lishuoboy.knife4j.swagger3_0_0.vo.RespVo;

/** 响应体包装 */
@RestControllerAdvice(basePackageClasses = {MyUserController.class})
public class MyResponseBodyControllerAdvice implements ResponseBodyAdvice<Object> {
    /** 支持哪些 */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // response 没有注释了 NotResponseBodyAdvice，且 不是ResultVo类型，且 不是String类型 才进行包装
        return !methodParameter.hasMethodAnnotation(NotResponseBodyAdvice.class)
            && !methodParameter.getParameterType().isAssignableFrom(RespVo.class)
            && !methodParameter.getParameterType().isAssignableFrom(String.class);
    }

    /* 写响应体之前的操作 */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return new RespVo(Code.SUCCESS, o);
    }
}